﻿using Microsoft.Extensions.Logging;
using PLCS.Application.Contracts.RoleApp;
using PLCS.Application.Contracts.RoleApp.Dtos;
using PLCS.Domain.Menus;
using PLCS.Domain.Roles;
using Volo.Abp.Domain.Repositories;

namespace PLCS.Application.RoleApp;

public class RoleAppService : ApplicationService, IRoleAppService
{
    private readonly IRepository<Role> _roleRespo;
    private readonly IRepository<Menu> _menuRespo;
    private readonly ILogger<RoleAppService> _logger;

    public RoleAppService(IRepository<Role> roleRepository, IRepository<Menu> menuRepository, ILogger<RoleAppService> logger)
    {
        _roleRespo = roleRepository;
        _menuRespo = menuRepository;
        _logger = logger;
    }

    /// <summary>
    /// 创建权限
    /// </summary>
    /// <param name="roleDto"></param>
    /// <returns></returns>
    public async Task CreateAsync(RoleEditDto roleDto)
    {
        if (!string.IsNullOrEmpty(roleDto.MenusString))
            await _roleRespo.InsertAsync(new Role(roleDto.RoleName, roleDto.Description, roleDto.MenusString));
        else
            await _roleRespo.InsertAsync(new Role(roleDto.RoleName, roleDto.Description));
    }

    /// <summary>
    /// 根据ID删除权限
    /// </summary>
    /// <param name="Id"></param>
    /// <returns></returns>
    public async Task DeleteAsync(Guid Id)
    {
        await _roleRespo.DeleteAsync(x => x.Id == Id);
    }

    /// <summary>
    /// 获取所有权限
    /// </summary>
    /// <returns></returns>
    public async Task<IEnumerable<RoleDto>> GetListAsync()
    {
        var res = await _roleRespo.GetListAsync();

        foreach (var item in res)
        {
            var menulist = item.Analysis();
            item.Menus = new List<Menu>();
            foreach (var menuitem in menulist)
            {
                var menu = await _menuRespo.FindAsync(x => x.Title == menuitem);
                foreach (var chilitem in await _menuRespo.GetListAsync())
                {
                    chilitem.Children = await _menuRespo.GetListAsync(x => x.Parent == chilitem);
                }
                item.Menus.Add(menu);
            }
        }
        return ObjectMapper.Map<List<Role>, List<RoleDto>>(res);
    }

    /// <summary>
    /// 更新权限
    /// </summary>
    /// <param name="roleDto"></param>
    /// <returns></returns>
    public async Task UpdateAsync(RoleEditDto roleDto)
    {
        _logger.LogInformation($"开始更新权限，权限名称为'{roleDto.RoleName}'");
        var model = await _roleRespo.GetAsync(x => x.Id == roleDto.Id);
        model.RoleName = roleDto.RoleName;
        model.Description = roleDto.Description;
        model.MenusString = roleDto.MenusString;
        await _roleRespo.UpdateAsync(model);
        _logger.LogInformation($"成功更新权限，权限名称为'{roleDto.RoleName}'");
    }
}